package com.hjm.common.utils;


import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

/**
 * @date 2020年10月15日
 */
public class MultipartFileToFile {

    /**
     * MultipartFile 转 File
     *
     * @param file
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {
        File toFile = null;
        InputStream ins = null;
        try{
            if ("".equals(file) || file.getSize() <= 0) {
                file = null;
            } else {

                ins = file.getInputStream();
                toFile = new File(UUID.randomUUID().toString()+"_"+file.getOriginalFilename());
                inputStreamToFile(ins, toFile);
            }
            return toFile;
        }catch (Exception e){
            throw e;
        }finally {
            if (null!=ins){
                ins.close();
            }
        }
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) throws Exception{
        OutputStream os =null;
        try {
            os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }

        } catch (Exception e) {
           throw e;
        }finally {
            if (null!=os){
                os.close();
            }
            if (null!=ins){
                ins.close();
            }

        }
    }

    /**
     * 删除本地临时文件
     * @param file
     */
    public static void delteTempFile(File file) {
        if (file != null) {
            File del = new File(file.toURI());
            del.delete();
        }
    }

}
